<template>
  <div class="login-container">
    <!-- logo区域 -->
    <div class="logo">
      <img src="../assets/logo.png" alt="">
    </div>

    <!-- 登录表单 -->
    <el-form ref="loginFormRef" :model="loginForm" :rules="loginFormRules" class="loginform-style">
      <!-- 登录名 -->
      <el-form-item prop="username">
        <el-input v-model="loginForm.username">
          <i slot="prefix" class="iconfont icon-user"></i>
        </el-input>
      </el-form-item>
    <!-- 密码 -->
      <el-form-item prop="password">
        <el-input v-model="loginForm.password" type="password">
          <i slot="prefix" class="iconfont icon-3702mima"></i>
        </el-input>
      </el-form-item>
      <!-- 按钮组 -->
      <el-form-item class="btns">
        <el-button type="primary" @click="login">登录</el-button>
        <el-button type="info" @click="resetForm">重置</el-button>
      </el-form-item>

    </el-form>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 表单数据
      loginForm: {
        username: 'admin',
        password: '123456'
      },
      // 表单验证规则
      loginFormRules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }, { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }, { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 登录
    login() {
      // 表单验证,回调的返回值是true或false
      this.$refs.loginFormRef.validate(async valid => {
        // 检验失败
        if (!valid) return
        // 校验成功,发登录请求
        const { data: res } = await this.$http.post('login', this.loginForm)
        // 登录失败
        if (res.meta.status !== 200) return this.$message.error('登录失败!')
        // 登录成功
        this.$message.success('登录成功!')
        // 将登录成功的令牌保存起来,供后续使用
        window.sessionStorage.setItem('token', res.data.token)
        // 跳转到后台首页
        this.$router.push('/home')
      })
    },
    // 重置
    resetForm() {
      this.$refs.loginFormRef.resetFields()
    }
  }
}
</script>
<style lang="less" scoped>
.login-container {
  position: absolute;
  top: 25%;
  left: 50%;
  transform: translateX(-50%);
  width: 450px;
  height: 304px;
  background-color: #fff;
  border-radius: 5px;

  // logo
  .logo {
    position: absolute;
    left: 50%;
    transform: translate(-50%, -60px);
    width: 130px;
    height: 130px;
    padding: 8px;
    background-color: #fff;
    border-radius: 50%;
    box-shadow: 0 0 10px #eee;
    img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      background-color: #eee;
    }
  }
  // 登录表单
  .loginform-style {
    padding: 0 20px;
    margin-top: 110px;
    .btns {
      // 伸缩布局
      display: flex;
      // 在主轴上的对齐方式
      justify-content: flex-end;
    }
  }
}
</style>
